package com.api.demo.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;

@RestController
@RequestMapping("/api/files")
@CrossOrigin(origins = "*", allowedHeaders = "*")
public class ResourceController {

    @Value("${file.upload-dir:uploads/avatars}")
    private String uploadDir;

    @GetMapping("/avatars/{filename:.+}")
    public ResponseEntity<Resource> serveFile(@PathVariable String filename) {
        try {
            // 构建文件路径
            String projectDir = new File("").getAbsolutePath();
            File file = new File(new File(projectDir, uploadDir), filename);
            System.out.println("尝试访问文件: " + file.getAbsolutePath());
            
            if (!file.exists()) {
                System.out.println("文件不存在: " + file.getAbsolutePath());
                
                // 尝试从classes目录获取
                File classesFile = new File(projectDir, "target/classes/" + uploadDir + "/" + filename);
                System.out.println("尝试从classes目录访问: " + classesFile.getAbsolutePath());
                
                if (classesFile.exists()) {
                    file = classesFile;
                    System.out.println("在classes目录找到文件");
                } else {
                    return ResponseEntity.notFound().build();
                }
            }
            
            // 创建资源
            Resource resource = new FileSystemResource(file);
            
            // 确定内容类型
            String contentType = determineContentType(filename);
            System.out.println("提供文件: " + file.getAbsolutePath() + ", 内容类型: " + contentType);
            
            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + filename + "\"")
                    .contentType(MediaType.parseMediaType(contentType))
                    .body(resource);
        } catch (Exception e) {
            System.err.println("提供文件时出错: " + e.getMessage());
            e.printStackTrace();
            return ResponseEntity.badRequest().build();
        }
    }
    
    private String determineContentType(String filename) {
        try {
            String extension = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();
            switch (extension) {
                case "png":
                    return "image/png";
                case "jpg":
                case "jpeg":
                    return "image/jpeg";
                case "gif":
                    return "image/gif";
                case "webp":
                    return "image/webp";
                default:
                    return "application/octet-stream";
            }
        } catch (Exception e) {
            return "application/octet-stream";
        }
    }
} 